const APICloud = require('apicloud-tools-core')
const path = require('path')
require('colors')
require('./lib/Date')

const ipcRenderer = require('electron').ipcRenderer;
const express_port = ipcRenderer.sendSync('get-express-port');


const txt_port = document.getElementById('txt_port')
const btn_start = document.getElementById('btn_start')
const txt_textarea = document.getElementById('txt_textarea')
btn_start.onclick = wifiStart;
txt_port.value = 'D:/Gitwork/herobuy-project/widget/dist:23456';
txt_textarea.value = `api.ajax({
    url:'http://${getIPAdress()}:${express_port}/tojson',
    headers:{
        'Content-Type': 'application/json;charset=utf-8'
    },
    method:'post',
    data:{
        body:ret
    }
    },function(res){
    console.log(res)
})
`


APICloud.wifiLog(({level,content})=>{
    if(level === "warn"){
        console.warn(content)
        return
    }
    if(level === "error"){
        console.error(content)
        return
    }
    try {
        console.log(JSON.parse(content))
    }catch(err){
        console.log(content)
    }

}).then(()=>{
        console.log("WiFi 日志服务已启动...")
    })


var socket = io('http://localhost:'+express_port);
socket.on('data:update',function(msg) {
    txt_textarea.value = JSON.stringify(msg.content)
    console.log(msg.content);
    console.log(('============='+msg.date+'=============').blue)
})

function wifiStart(){
    let port = directoryPort(txt_port.value).port
    APICloud.startWifi({port: port})
    btn_start.onclick = wifiStop;
    btn_start.innerText = '关闭Wifi服务';
}
function wifiStop(){
    let port = directoryPort(txt_port.value).port
    APICloud.endWifi({port: port})
    btn_start.onclick = wifiStart;
    btn_start.innerText = '启动Wifi服务';
}

function wifiSync(isSyncAll=false) {
    let dir = directoryPort(txt_port.value).directory
    APICloud.syncWifi({
        projectPath:path.resolve(dir),
        syncAll:isSyncAll
    })
}


function directoryPort(txt) {
    let arr = txt.split(":")
    if(arr.length==0){
        console.error('请输入地址和端口号以:分开')
        return false
    }
    return {
        directory:arr[0]+':'+arr[1],
        port:parseInt(arr[2])
    }
}

function getIPAdress(){
    var interfaces = require('os').networkInterfaces();
    for(var devName in interfaces){
        var iface = interfaces[devName];
        for(var i=0;i<iface.length;i++){
            var alias = iface[i];
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address;
            }
        }
    }
}

